package com.yncmcc.Controller;

import com.yncmcc.Controller.Interface.AdminController;
import com.yncmcc.Entity.*;
import com.yncmcc.Service.Interface.*;
import com.yncmcc.Util.MD5Util;
import com.yncmcc.Util.RSAUtils;
import com.yncmcc.Util.STATUS;
import jxl.read.biff.BiffException;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.StringUtils;
//import org.apache.shiro.SecurityUtils;
//import org.apache.shiro.authc.AuthenticationException;
//import org.apache.shiro.authc.IncorrectCredentialsException;
//import org.apache.shiro.authc.UnknownAccountException;
//import org.apache.shiro.authc.UsernamePasswordToken;
//import org.apache.shiro.subject.Subject;
//import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.security.interfaces.RSAPublicKey;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by CMCC-sunmo on 2016/9/18.
 */
@Controller
@RequestMapping("/admin")
public class AdminControllerImpl implements AdminController {
    @Autowired
    private UserService userService;
    @Autowired
    private ContractsService contractsService;
    @Autowired
    private PeriodService periodService;
    @Autowired
    private AdminService adminService;
    @Autowired
    private LogsService logsService;
    private  Map<String , Object> response;

    public AdminControllerImpl() {
        super();
    }

    @Override
    @ResponseBody
    @RequestMapping(value = "/addContract", method = RequestMethod.POST)
    public Map<String, Object> addContract(ContractsEntity contractsEntity, HttpServletRequest request, HttpSession session) {
        response = new HashMap();
        UserEntity userEntity = userService.findByUserName(contractsEntity.getUserId());
        contractsEntity.setDeptId(userEntity.getDeptId());
        contractsEntity.setUserId(userEntity.getUserId());
        String des = contractsService.addContract(contractsEntity);
        if(des.equals("ok")){
            response.put("status" , "ok");
            response.put("des" , "合同添加成功");
            return response;
        }else{
            response.put("status" , "ok");
            response.put("des" , des);
            return response;
        }
    }

    @Override
    @ResponseBody
    @RequestMapping(value = "/addPeriod", method = RequestMethod.POST)
    public Map<String, Object> addPeriod(PeriodEntity periodEntity, HttpServletRequest request, HttpSession session) {
        response = new HashMap();
        String flag  = periodService.addPeriod(periodEntity);
        if(flag.equals("ok")){
            response.put("status" , "ok");
            response.put("des" , "合同分期添加成功");
            return response;
        }else{
            response.put("status" , "ok");
            response.put("des" , flag);
            return response;
        }
    }

    @Override
    @ResponseBody
    @RequestMapping(value = "/getContractByID", method = RequestMethod.GET)
    public Map<String, Object> getContractByID(String contractId, HttpServletRequest request, HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        ContractsEntity contractsEntity = contractsService.findByContractID(contractId);
        contractsEntity.setUserId(userService.findByUserId(contractsEntity.getUserId()).getUserName());
        if (null == contractsEntity) {
            response.put("status", "error");
            response.put("des", "合同不存在");
            return response;
        }
        else {
            response.put("status", "ok");
            response.put("des", "成功");
            response.put("data", contractsEntity);
            return response;
        }
    }

    @Override
    @ResponseBody
    @RequestMapping(value = "/getPeriodByCID", method = RequestMethod.GET)
    public Map<String, Object> getPeriodByCID(String contractId, HttpServletRequest request, HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        List<PeriodEntity> periodEntities = periodService.findByContractId(contractId);
        if (null == periodEntities) {
            response.put("status", "error");
            response.put("des", "本合同没有分期");
            return response;
        }
        else {
            response.put("status", "ok");
            response.put("des", "成功");
            response.put("data", periodEntities);
            return response;
        }
    }

    @Override
    @ResponseBody
    @RequestMapping(value = "/addContractByExcel", method = RequestMethod.POST)
    public Map<String, Object> addContractByExcel(MultipartFile file, HttpServletRequest request, HttpSession session) throws IOException, BiffException, ParseException {
        response = new HashMap<>();

        if(file == null){
            response.put("status","empty");
            response.put("description", "文件为空");
            return response;
        }

        String message = contractsService.addByExcel(file);
        if (StringUtils.isBlank(message)) {
            response.put("status", "ok");
            response.put("description", "批量导入成功");
        }
        else {
            response.put("status", "error");
            response.put("description", message);
        }
        return response;
    }

    @Override
    @ResponseBody
    @RequestMapping(value = "/findContract", method = RequestMethod.POST)
    public Map<String, Object> findContract(ContractsEntity contractsEntity, HttpServletRequest request, HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        List<ContractsCustomEntity> contractsEntities = contractsService.findReqContract(contractsEntity);
        if (null == contractsEntities || contractsEntities.size() == 0) {
            response.put("status", "error");
            response.put("des", "合同不存在");
            response.put("data",null);
            return response;
        }else {
            response.put("status", "ok");
            response.put("des", "成功");
            response.put("data", contractsEntities);
            return response;
        }
    }

    @Override
    @ResponseBody
    @RequestMapping(value = "/updateContract", method = RequestMethod.POST)
    public Map<String, Object> updateContract(ContractsEntity contractsEntity, HttpServletRequest request, HttpSession session) {
        response = new HashMap<>();
        if (session.getAttribute("adminId").equals("null")) {
            response.put("status", "refuse");
            response.put("des", "未登录");
            return response;
        }

        if (StringUtils.isBlank(contractsEntity.getContractId()) || StringUtils.isBlank(contractsEntity.getContractName())) {
            response.put("status", "error");
            response.put("des", "合同号或合同名为空");
            return response;
        }

        ContractsEntity oldContract = contractsService.findByContractID(contractsEntity.getContractId());//原来的合同信息

        if (null == oldContract) {
            response.put("status", "error");
            response.put("des", "合同不存在");
            return response;
        }
        oldContract.setContractId(contractsEntity.getContractId());
        oldContract.setContractSerial(contractsEntity.getContractSerial());
        oldContract.setUserId(userService.findByUserName(contractsEntity.getUserId()).getUserId());
        oldContract.setContractCate(contractsEntity.getContractCate());//修改合同类型
        oldContract.setContractName(contractsEntity.getContractName());
        String cate = oldContract.getContractCate() + "";

        if(cate.equals("1")) {
            oldContract.setSrStartTime(contractsEntity.getSrStartTime());
            oldContract.setSrEndTime(contractsEntity.getSrEndTime());
            oldContract.setSrRemindTime(contractsEntity.getSrRemindTime());
            oldContract.setSrIsWarn(contractsEntity.getSrIsWarn());
        }
        else if(cate.equals("2")){
            oldContract.setEaStartTime(contractsEntity.getSrStartTime());
            oldContract.setEaEndTime(contractsEntity.getEaEndTime());
            oldContract.setEaRemindTime(contractsEntity.getEaRemindTime());
            oldContract.setEaIsWarn(contractsEntity.getEaIsWarn());
        }
        else if(cate.equals("3")){
            oldContract.setCtStartTime(contractsEntity.getCtStartTime());
            oldContract.setCtEndTime(contractsEntity.getCtEndTime());
            oldContract.setCtRemindTime(contractsEntity.getCtRemindTime());
            oldContract.setCtPeriodNum(contractsEntity.getCtPeriodNum());
            oldContract.setCtIsWarn(contractsEntity.getCtIsWarn());
        }
        else{
            response.put("status", "error");
            response.put("des", "请先输入合同类型，再进行修改");
            return response;
        }

        int status = contractsService.updateContract(oldContract);
        if (status == STATUS.MINUS) {
            response.put("status", "minus");
            response.put("des", "金额不可为负数");
        }
        if (status == STATUS.STARTTIMEERROR) {
            response.put("status", "startTimeError");
            response.put("des", "起始时间非法");
        }
        if (status == STATUS.DEADLINEERROR) {
            response.put("status", "startTimeError");
            response.put("des", "截止时间非法");
        }
        if (status == STATUS.REMINDTIMEERROR) {
            response.put("status", "remindTimeError");
            response.put("des", "提醒时间非法");
        }
        if (status == STATUS.ID_EMPTY) {
            response.put("status", "empty");
            response.put("des", "合同不存在");
        }
        if (status == STATUS.SUCCESS) {
            response.put("status", "ok");
            response.put("des", "修改成功");
        }
        return response;
    }

    @Override
    @ResponseBody
    @RequestMapping(value = "/deleteContract", method = RequestMethod.GET)
    public Map<String, Object> deleteContract(String ContractId, HttpServletRequest request, HttpSession session) {
        response = new HashMap();
        ContractsEntity check = contractsService.findByContractID(ContractId);
        if(null == check){
            response.put("status" , "error");
            response.put("des" , "删除的合同不存在");
            return response;
        }else if(check.getContractCate() == 3){
            String flag2 = periodService.deletePeriodByContractId(ContractId);
            if(!flag2.equals("ok")){
                response.put("status" , "error");
                response.put("des" ,flag2);
                return response;
            }
        }
        String  flag1 = contractsService.deleteContract(ContractId);
        if(!flag1.equals("ok")){
            response.put("status" , "error");
            response.put("des" , flag1);
            return response;
        }else{
            response.put("status" , "ok");
            response.put("des" , "删除合同成功");
        }
        return response;
    }

    @Override
    @ResponseBody
    @RequestMapping(value = "/addUser", method = RequestMethod.POST)
    public Map<String, Object> addUser(UserEntity userEntity, HttpServletRequest request, HttpSession session) {
        response = new HashMap();
        String  flag = userService.addUser(userEntity);
        if(flag.equals("ok")){
            response.put("status" , "ok");
            response.put("des" , "用户添加成功");
            return response;
        }else{
            response.put("status" , "error");
            response.put("des" , flag);
            return response;
        }
    }

    @Override
    @ResponseBody
    @RequestMapping(value = "/addUserByExcel", method = RequestMethod.POST)
    public Map<String, Object> addUserByExcel(MultipartFile file, HttpServletRequest request, HttpSession session) throws IOException, BiffException, ParseException {
        Map<String, Object> response = new HashMap<String, Object>();
        if (file == null) {
            response.put("status", "empty");
            response.put("description", "提交文件为空");
            return response;
        }
        String message = userService.addUserByExcel(file);

        if (StringUtils.isBlank(message)) {
            response.put("status", "ok");
            response.put("des", "导入用户成功");
        } else {
            response.put("status", "error");
            response.put("des", message);
        }
        return response;
    }

    @Override
    @ResponseBody
    @RequestMapping(value = "/findUser", method = RequestMethod.POST)
    public Map<String, Object> findUser(UserEntity userEntity, HttpServletRequest request, HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        //deptId,userId,contractSerial,contractName,contractCate,
        //IsWarn,contractCTime,contractUTime

        List<UserEntity> userEntities = userService.findUser(userEntity);

        if (null == userEntities || userEntities.size() == 0) {
            response.put("status", "error");
            response.put("des", "用户不存在");
            response.put("data",null);
            return response;
        }else {
            response.put("status", "ok");
            response.put("des", "成功");
            response.put("data", userEntities);
            return response;
        }
    }

    @Override
    @ResponseBody
    @RequestMapping(value = "/getUserfInfo", method = RequestMethod.GET)
    public Map<String, Object> getUser(String userId, HttpServletRequest request, HttpSession session) {
        response = new HashMap();
        UserEntity check = userService.findByUserId(userId);
        if(check == null){
            response.put("status" , "error");
            response.put("des" , "查询用户不存在");
            return response;
        }else{
            response.put("status" , "ok");
            response.put("des" , "查询成功");
            response.put("data" , check);
            return response;
        }
    }

    @Override
    @ResponseBody
    @RequestMapping(value = "/updateUserInfo", method = RequestMethod.POST)
    public Map<String, Object> updateUser(UserEntity userEntity, HttpServletRequest request, HttpSession session) {
        response = new HashMap();
        if(StringUtils.isBlank(userEntity.getUserName())){
            response.put("status" , "error");
            response.put("des" , "用户名为空");
            return response;
        }else if(StringUtils.isBlank(userEntity.getUserId())){
            response.put("status" , "error");
            response.put("des" , "用户ID为空");
            return response;
        }else if(StringUtils.isBlank(userEntity.getDeptId())){
            response.put("status" , "error");
            response.put("des" , "用户部门为空");
            return response;
        }else if(StringUtils.isBlank(userEntity.getUserOaEmail())){
            response.put("status" , "error");
            response.put("des" , "用户OA邮箱为空");
            return response;
        }else if(StringUtils.isBlank(userEntity.getUserOrdinaryEmail())){
            response.put("status" , "error");
            response.put("des" , "用户名普通邮箱为空");
            return response;
        }else if(StringUtils.isBlank(userEntity.getUserFullName())){
            response.put("status" , "error");
            response.put("des" , "用户姓名为空");
            return response;
        }else if(StringUtils.isBlank(userEntity.getUserPhone())){
            response.put("status" , "error");
            response.put("des" , "用户电话为空");
            return response;
        }else if(userEntity.getUserRight() == null) {
            response.put("status" , "error");
            response.put("des" , "用户权限不为空");
            return response;
        }
        String  flag = userService.updateUser(userEntity);
        if(flag.equals("ok")){
            response.put("status" , "ok");
            response.put("des" , "更新成功");
            return response;
        }else{
            response.put("status" , "error");
            response.put("des" , flag);
            return response;
        }
    }

    @Override
    @ResponseBody
    @RequestMapping(value = "/resetUserPass", method = RequestMethod.POST)
    public Map<String, Object> resetUserPass(String userId, String newPass, HttpServletRequest request, HttpSession session) {
        response = new HashMap();
        UserEntity check = userService.findByUserId(userId);
        if(check == null){
            response.put("status" , "error");
            response.put("des" , "用户不存在");
            return response;
        }else if(StringUtils.isBlank(newPass)){
            response.put("status" , "error");
            response.put("des" , "密码不为空");
            return response;
        }else{
            check.setUserPass(MD5Util.calc(newPass+check.getUserPrimarySalt()));
            String flag = userService.updateUser(check);
            if (flag.equals("ok")){
                response.put("status" , "ok");
                response.put("des" , "用户密码重置成功，新密码为123456");
                return response;
            }else{
                response.put("status" , "error");
                response.put("des" , flag);
                return response;
            }
        }
    }

    @Override
    @ResponseBody
    @RequestMapping(value = "/deleteUser", method = RequestMethod.POST)
    public Map<String, Object> deleteUser(String userId, HttpServletRequest request, HttpSession session) {
        response = new HashMap();
        UserEntity check = userService.findByUserId(userId);
        if(check == null){
            response.put("status" , "error");
            response.put("des" , "删除用户不存在");
            return response;
        }else{
            String flag = userService.deleteUser(userId);
            if(flag.equals("ok")){
                response.put("status" , "ok");
                response.put("des" , "删除成功");
            }else{
                response.put("status" , "error");
                response.put("des" , flag);
            }
        }
        return response;
    }

    @Override
    @ResponseBody
    @RequestMapping(value = "/findLog", method = RequestMethod.POST)
    public Map<String, Object> findLog(LogsEntity logsEntity, HttpServletRequest request, HttpSession session) {
        Map<String, Object> response = new HashMap<>();

        List<LogsCustomEntity> logsCustomEntities = logsService.findLog(logsEntity);

        if (null == logsCustomEntities || logsCustomEntities.size() == 0) {
            response.put("status", "error");
            response.put("des", "日志不存在");
            response.put("data",null);
            return response;
        }else {
            response.put("status", "ok");
            response.put("des", "成功");
            response.put("data", logsCustomEntities);
            return response;
        }

    }

    @Override
    @ResponseBody
    @RequestMapping(value = "/deleteLog", method = RequestMethod.GET)
    public Map<String, Object> deleteLog(String logId, HttpServletRequest request, HttpSession session) {
        response = new HashMap();

        String flag = logsService.deleteLog(logId);
        if(flag.equals("ok")){
            response.put("status" , "ok");
            response.put("des" , "删除日志成功");
        }else{
            response.put("status" , "error");
            response.put("des" , flag);
        }
        return response;
    }

    @Override
    @ResponseBody
    @RequestMapping(value = "/addAdmin", method = RequestMethod.POST)
    public Map<String, Object> addAdmin(String adminName, String adminPass, HttpServletRequest request, HttpSession session) {
        response = new HashMap();
        AdminEntity check = adminService.findByAdminName(adminName);
        if(check != null){
            response.put("status" , "error");
            response.put("des" , "管理员已存在");
            return response;
        }else if(StringUtils.isBlank(adminPass)){
            response.put("status" , "error");
            response.put("des" , "密码为空");
            return response;
        }else{
            AdminEntity adminEntity = new AdminEntity();
            adminEntity.setAdminName(adminName);
            adminEntity.setAdminPass(adminPass);
            adminService.addAdmin(adminEntity);
            response.put("status" , "ok");
            response.put("des" , "添加成功");
            return response;
        }
    }

    @Override
    @ResponseBody
    @RequestMapping(value = "/getSelfInfo", method = RequestMethod.GET)
    public Map<String, Object> getSelfInfo(HttpServletRequest request, HttpSession session) {
        response = new HashMap();
        String adminId = (String) session.getAttribute("adminId");
        AdminEntity adminEntity = adminService.findAdminById(adminId);
        if(adminEntity == null){
            response.put("status" , "error");
            response.put("des" , "所查管理员不存在");
            return response;
        }else{
            response.put("status" , "ok");
            response.put("des" , "成功");
            response.put("data" , adminEntity);
            return response;
        }
    }

    @Override
    @ResponseBody
    @RequestMapping(value = "/updatePass", method = RequestMethod.POST)
    public Map<String, Object> updatePass(String adminId, String oldPassword, String newPassword) {
        response = new HashMap();
        AdminEntity adminEntity = adminService.findAdminById(adminId);
        if(adminEntity == null){
            response.put("status" , "error");
            response.put("des" , "所查管理员不存在");
            return response;
        }else if(StringUtils.isBlank(oldPassword)){
            response.put("status" , "error");
            response.put("des" , "密码为空");
            return response;
        }else if(StringUtils.isBlank(newPassword)){
            response.put("status" , "error");
            response.put("des" , "新密码为空");
            return response;
        }
        if(!adminService.checkPass(adminId , oldPassword)){
            response.put("status" , "error");
            response.put("des" , "旧密码错误");
            return response;
        }else{
            adminEntity.setAdminPass(newPassword);
            adminService.updateAdmin(adminEntity);
            response.put("status" , "ok");
            response.put("des" , "密码修改成功");
            return response;
        }
    }

    @Override
    @ResponseBody
    @RequestMapping(value = "/updatePeriod", method = RequestMethod.POST)
    public Map<String, Object> updatePeriod(PeriodEntity periodEntity, HttpServletRequest request, HttpSession session) {
        response = new HashMap();
        String  flag  = periodService.updatePeriod(periodEntity);
        if(flag.equals("ok")){
            response.put("status" , "ok");
            response.put("des" , "合同分期更新成功");
            return response;
        }else{
            response.put("status" , "error");
            response.put("des" , flag);
            return response;
        }
    }

    @Override
    @RequestMapping(value = "/**")
    public String errorAction() {
//        request.getRequestDispatcher(request.getContextPath()+"/login.jsp").forward(request,response);
        return "forward:/login.jsp";
    }
}
